#include "light.h"
#include "uart.h"

light* light_alloc(uint16_t lux)
{
	light *l = (light*) malloc(sizeof(light));
	if(l == NULL) {
		return NULL;
	}
	l->_lux = lux;
	return l;
}

void light_free(light *l)
{
	free(l);
}

double calc_triangle(int m, int d, int x)
{
	float rtrn = 0.0;
	if(((m - d) <= x) && (x <= (m + d))) {
		float tmp = (float)(m - x) / d;
		if(tmp < 0.0) {
			tmp *= -1.0;
		}
		rtrn = 1.0 - tmp;
	}
	return rtrn;
}

/*
 * We have following input fuzzy-sets:
 * 0   - 150 lux ... dark 		m = 0; 		d = 150
 * 125 - 375 lux ... normal		m = 250; 	d = 125
 * 350 - 500 lux ... bright		m = 500;	d = 150
 * Triangle-Function
 * Um,d = {1 - |(m-d)/ld|, if m-d <=  x <= m+d ;; 0, if x < m-d or x > m + d}
 */
uint8_t light_calc(light *l)
{
	if(l == NULL) {
		return 0;
	}
	uint16_t x = l->_lux;
	// first of all, fuzzyfication
	float dark = calc_triangle(0, 250, x);
	float normal = calc_triangle(250, 125, x);
	float bright = calc_triangle(500, 150, x);

	// calculating the output-crisp-value...
	return (uint8_t)(7.0 * dark + 5.0 * normal + 0.0 * bright);
}

